<template>
  <div>
    <div class="shop-box" v-for="item in shop" :key="item.id">
      <van-row type="flex" align="center" style="margin: 10px 0">
        <van-col span="2">
          <van-checkbox v-model="item.checked" />
        </van-col>
        <van-col span="22">
          <van-card
            :num="item.count"
            :price="item.money"
            :desc="item.label"
            :title="item.title"
            :thumb="item.src"
          >
            <div slot="footer">
              ￥{{ item.money * item.count }}
              <van-stepper v-model="item.count" />
            </div>
          </van-card>
        </van-col>
      </van-row>
    </div>
    <!-- 结算操作 -->
    <van-submit-bar
      style="bottom: 50px"
      :price="total * 100"
      button-text="提交订单"
      @submit="onSubmit"
    >
      <van-checkbox v-model="allChecked">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
import { mapState, } from "vuex";
export default {
  name: "shop",
  data() {
    return {
      value: 1,
      total: 0,
      allChecked: false
    };
  },
  computed: {
    ...mapState(["shop"])
  },
  mounted() {
    // eslint-disable-next-line no-console
    // console.log(this.shop);
  },
  methods: {
    onSubmit() {
      // 1.判断总价是否合法--不为0
      if (this.total) {
        // 循环查找商品的id值，通过checked === true
        let ids = [];
        this.shop.forEach(item => {
          if (item.checked) {
            ids.push(item.id);
          }
        });
        this.$router.push({
          path: "/submit/shop1001",
          query: { total: this.total, spid: ids }
        });
      }
    }
  },
  //触发单选框时

  watch: {
    shop: {
      handler(newVal) {
        // 钱--用来计算每一条的数量+单价
        let money = 0;
        // 选中的条数
        let checked = 0;
        // 逻辑--循环
        newVal.forEach(item => {
          // 通过checked判断
          if (item.checked) {
            money += item.count * item.money;
            checked++;
          }
        });
        this.total = money;
        // 如果选中的条数等于数组的长度说明全选了
        if (checked === newVal.length) {
          this.allChecked = true;
        } else {
          this.allChecked = false;
        }
      },
      deep: true // 深度监听
      //immediate: true // 第一次立即执行一次监听
    }
  }
};
</script>

<style></style>
